#include "buffer.h"

myFILE *my_fopen(const char *pathname, const char *mode)
{
    //先判断打开的选项
    int flag = 0;
    if(strcmp(mode,"r") == 0) 
        flag |= O_RDONLY;
    else if(strcmp(mode,"w") == 0)
        flag |= (O_WRONLY|O_CREAT|O_TRUNC);
    else if(strcmp(mode,"a") == 0)
        flag |= (O_WRONLY|O_CREAT|O_APPEND);
    else
        return NULL;

    //打开文件，如果没有就会创建一个
    int fd = 0;
    if(flag & O_WRONLY)
    {
        umask(0);       //权限掩码设置为0
        fd = open(pathname,flag,0666);
    }
    else
    {
        fd = open(pathname,flag);
    }
    if(fd < 0) return NULL;     //打开失败

    //开辟空间和初始化
    myFILE* fp = (myFILE*)malloc(sizeof(myFILE));
    if(fp == NULL) return NULL;
    fp->fileno = fd;
    fp->cap = SIZE;
    fp->pos = 0;
    fp->flush_mode = LINE_FLUSH;

    return fp;
}

int my_fwrite(myFILE *fp, const char *s, int size)
{
    //先写入到缓冲区
    memcpy(fp->outbuffer+fp->pos,s,size);
    fp->pos +=size;

    //判断刷新
    if(fp->flush_mode == LINE_FLUSH && fp->outbuffer[fp->pos - 1] == '\n')
        my_fflush(fp);
    else if(fp->flush_mode == FULL_FLUSH && fp->pos == fp->cap)
        my_fflush(fp);

    return size;
}

//int my_fread();
void my_fflush(myFILE *fp)          //刷新缓冲区
{
    if(fp->pos == 0) return;            //缓冲区为0
    write(fp->fileno,fp->outbuffer,fp->pos);    //写到文件描述符位置
    fp->pos = 0;                        //缓冲区从0开始
}

void my_fclose(myFILE *fp)          //关闭文件
{
    my_fflush(fp);              //刷新缓冲区
    close(fp->fileno);          //关闭
    free(fp);                   //释放空间
}

const char *toString(int flag)      //转字符串
{
    if(flag & NONE_FLUSH) return "None";
    else if(flag & LINE_FLUSH) return "LINE";
    else if(flag & FULL_FLUSH) return "FULL";
    return "UNKNOW";
}

void DebugPrint(myFILE *fp)         //打印
{
    printf("outbufer: %s\n", fp->outbuffer);
    printf("fd: %d\n", fp->fileno);
    printf("pos: %d\n", fp->pos);
    printf("cap: %d\n", fp->cap);
    printf("flush_mode: %s\n", toString(fp->flush_mode));
}